import { combineReducers } from 'redux'
import {SETCOURSE,GETCOURSE,AJAXERROR,DELCOURSE,REFRESH,SORT,getCourseList,SEARCH,FILTER,CHANGEPAGE,SELECTCOURSE,MOVE,ADDCOURSE,DELITEM} from "../../actions/admin/course_edit_actions"
require("../toastr")

const initialState = {
    course : {},

    courses : [],           // 课程列表数据
    cachedCourses : [],      // 缓存的数据
    page : 1,               // 当前页数
    limit : 10,             // 每页个数
    totalCount : 0,          // 所有课程的数目
    selectedCourses : []      // 被选中的课程
}

/**
 * sortIdx转换成对象的属性
 * @param sortIdx
 * @returns {*}
 */
function idx2Property(sortIdx){
    switch(sortIdx){
        case 1:
            return "id"
        case 2:
            return "title"
        case 3:
            return "description"
        case 4:
            return "cover"
        default:
            return null

    }
}

function courseEdit(state = initialState,action){
    switch(action.type){
        case GETCOURSE :
            var course = action.course
            return Object.assign({},state,{
                course : course
            })

        case AJAXERROR:
            if(process.env.DEBUG !== null && typeof process.env.DEBUG !== "undefined"){
                console.error(action.message)
            }
            toastr.error("网络错误")
            return state

        case SETCOURSE:
            var course = action.course
            return Object.assign({},state,{
                course : course
            })

        case DELCOURSE:
            location.href = "/admin_home/course"
            return state

        case REFRESH:
            toastr.success("获取列表成功")
            action.courses.sort((a,b) => {      // 按照创建时间排序
                return new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
            })
            return Object.assign({},state,{
                courses : action.courses,
                cachedCourses : action.courses,
                page : 1,
                limit : 10
            })

        case SORT:
            var newCourses = Array.prototype.concat.apply([],state.courses)
            // console.log(newCourses)
            var propertyName = idx2Property(action.sortIdx)
            if(! propertyName){
                return state
            }
            newCourses = newCourses.sort((a,b) => {
                var aProperty = a[propertyName],
                    bProperty = b[propertyName]
                if(typeof aProperty == "number"){
                    return action.sortFlag ? bProperty - aProperty : aProperty - bProperty
                }else if(typeof aProperty == "string"){
                    return action.sortFlag ? bProperty.localeCompare(aProperty) : aProperty.localeCompare(bProperty)
                }
            })
            return Object.assign({},state,{
                courses: newCourses
            })

        case SEARCH:
            let re = new RegExp(action.searchText,"gi")
            let newCourses = state.cachedCourses.filter((e,idx) => {
                let flag = false
                Object.getOwnPropertyNames(e).forEach((key,i) => {
                    if(re.test(e[key])){
                        flag = true
                    }
                })
                return flag
            })
            // console.log(newCourses)
            return Object.assign({},state,{
                courses : newCourses
            })

        case FILTER:
            var filterName = action.filterName
            var newCourses = filterName === "全部" ?
                state.cachedCourses :
                state.cachedCourses.filter((e,idx) => {
                    return e["major"] === filterName
                })

            return Object.assign({},state,{
                courses : newCourses
            })

        case CHANGEPAGE:
            var page = action.page
            var limit = action.limit
            var newCourses = state.cachedCourses.slice((page - 1) * limit,page * limit)

            return Object.assign({},state,{
                courses : newCourses,
                selectedCourses : []        // 清空已选课程
            })

        case SELECTCOURSE:
            var course = action.course
            var selectedCourses = Array.prototype.concat.apply([],state.selectedCourses)

            // 是否已被选中
            var flag = 0
            for(var c of selectedCourses){
                if(c && c.id){      // id非0
                    if(c.id == course.id){
                        flag = 1
                    }
                }else{
                    return state
                }
            }
            if(flag){
                selectedCourses.splice(selectedCourses.indexOf(course),1)
            }else{
                selectedCourses.push(course)
            }
            return Object.assign({},state,{
                selectedCourses : selectedCourses
            })

        case MOVE :
            var direction = action.direction
            var course = action.course
            var newCourses = Array.prototype.concat.apply([],state.courses)

            var temp,idx
            idx = newCourses.indexOf(course)
            if((idx == 0 && direction == "up") || (idx == newCourses.length && direction == "down")){
                return state
            }

            if(direction == "up"){
                temp = newCourses[idx]
                newCourses[idx] = newCourses[idx - 1]
                newCourses[idx - 1] = temp
            }else if(direction == "down"){
                temp = newCourses[idx]
                newCourses[idx] = newCourses[idx + 1]
                newCourses[idx + 1] = temp
            }else {
                return state
            }

            return Object.assign({},state,{
                courses : newCourses
            })

        case ADDCOURSE:
            var course = action.course
            var newCourses = Array.prototype.concat.apply([],state.courses)
            newCourses.unshift(course)

            return Object.assign({},state,{
                courses : newCourses
            })

        case DELITEM:
            var course = action.course
            var newCourses = Array.prototype.concat.apply([],state.courses)

            var delIdx
            for(var i = 0; i < newCourses.length; i ++){
                if(newCourses[i].id == action.id){
                    delIdx = i
                    break
                }
            }
            if(delIdx !== null){
                newCourses.splice(delIdx,1)
            }

            return Object.assign({},state,{
                courses : newCourses
            })

        default:
            return state
    }
}

const courseEditApp = combineReducers({
    courseEdit
})

export default courseEditApp